<?php
// If we are an admin we need to load some site-wide javascripts
if ($GLOBALS['authNamespace']->admin) {
	$headers->headScript()->appendFile("./libs/inlineEdit.v3.js");
	$headers->headScript()->appendFile("./libs/datepicker.js");
	$headers->headScript()->appendFile("./modules/admin/admin.js");
}

function admin_onLoad($db) {
	require_once './libs/phpbb.php';
	if (!empty($GLOBALS['config']['forumdir']))
		$phpbb = new Zend_PHPBB3($GLOBALS['config']['forumdir']);
	// Set table name
	if (!empty($_REQUEST['type'])) {
		if ($_REQUEST['type'] == 'news')
			$table = 'news';
		else
			$table = 'articles';
	}
	// Check login
	if (!empty($_POST['submit'])) {
		$row = $db->fetchRow("SELECT rootuser,rootpassword FROM config");
        if ($row['rootuser'] == $_POST['login'] && $row['rootpassword'] == sha1($_POST['pass'])) {
			// Session namespace
        	$GLOBALS['authNamespace']->user = $_POST['login'];
        	$GLOBALS['authNamespace']->admin = true;
			$GLOBALS['logger']->log('Successful admin login from ' . $_SERVER['REMOTE_ADDR'] , Zend_Log::NOTICE);
        } else {
			$GLOBALS['view']->assign('error_msg', 'Wrong username or password.');
			$GLOBALS['logger']->log('Unsuccessful admin login from ' . $_SERVER['REMOTE_ADDR'] , Zend_Log::WARN);
		}
	}
	// Delete content
	elseif (isset($_GET['action']) && $_GET['action'] == 'delete' && $GLOBALS['authNamespace']->admin) {
		$db->delete($table, 'id = ' . $db->quote($_GET['id']));
		header("Location: index.php?mod=admin&action=manage&type=" . $_GET['type']);
		exit;		
	}
	// Save submitted content
	elseif (!empty($_POST['savecontent']) && $GLOBALS['authNamespace']->admin) {
		if (isset($_POST['published']))
			$published = 1;
		else
			$published = 0;
		if (isset($_POST['menu']))
			$menu = 1;
		else
			$menu = 0;
		if (!empty($_POST['id'])) {
			$old = $db->fetchRow("SELECT content,comments,moddate FROM $table WHERE id = " . $db->quote($_POST['id']));
			if ($old['content'] != $_POST['content'])
				$moddate = new Zend_Db_Expr('NOW()');
			else
				$moddate = $old['moddate'];
			// Set phpBB approved flag
			if (isset($phpbb)) {
				if (isset($_POST['comments'])) {
					// If comments were off before we may need to create a new topic now
					if ($old['comments'] > 0)
						$phpbb->set_approved($old['comments']);
					else
						$needsIntro = true;
				}
				else
					$phpbb->set_approved($old['comments'], FALSE);
			}
			else
				$old['comments'] = 0;
			$data = array('title' => $_POST['title'],
						'content' => $_POST['content'],
						'tags' => $_POST['tags'],
						'comments' => $old['comments'],
						'published' => $published,
						'moddate' => $moddate);
			if ($table == 'news') {
				if (isset($_POST['sticky']))
			    	$data['sticky'] = 1;
				else
				    $data['sticky'] = 0;
			}
			$db->update($table, $data, 'id = ' . $db->quote($_POST['id']));
			$count = $db->fetchOne("SELECT COUNT(*) FROM menu WHERE parent = 2 AND link LIKE '%mod=article&id=" . $db->quote((int)$_POST['id']) . "'");
		}
		else {
			// Submission callback
			foreach ($GLOBALS['modloaded'] as $v) {
				if (function_exists($v.'_onSubmit'))
					call_user_func($v.'_onSubmit', $_POST['title'], $_POST['content'], $_POST['tags']);
			}
			// Save new data
			$data = array('title' => $_POST['title'],
						  'content' => $_POST['content'],
						  'tags' => $_POST['tags'],
						  'published' => $published,
						  'pubdate' => new Zend_Db_Expr('NOW()'));
			if ($table == 'news') {
				if (isset($_POST['sticky']))
			    	$data['sticky'] = 1;
				else
				    $data['sticky'] = 0;
			}
			$db->insert($table, $data);
			$_POST['id'] = $db->lastInsertId();
			$needsIntro = true;
			$count = 0;
		}
		// Create a new phpBB topic
		if (isset($phpbb) && isset($needsIntro)) {
			$url = $GLOBALS['config']['siteURL'] . '?mod=' . $_GET['type'] . '&amp;id=' . $_POST['id'];
			$intro = str_replace(array("%t", "%u", "%c"), array($_POST['title'], $url, $_POST['content']), $GLOBALS['config']['threadintro']);
			$topic_id = $phpbb->create_topic($_POST['title'], $intro, $GLOBALS['config']['forumid']);
			$db->update($table, array('comments' => $topic_id), 'id = ' . $_POST['id']);	
		}
		// Add, edit or remove a link on our menu
		$last_weight = $db->fetchOne("SELECT weight FROM menu WHERE parent = 2 ORDER BY weight DESC LIMIT 1");
		if ($table == 'articles' && $published == 1 && $menu == 1 && $count < 1)
			$db->insert('menu', array('name' => $_POST['title'], 'link' => 'index.php?mod=article&id=' . $_POST['id'], 'parent' => 2, 'weight' => ($last_weight + 1)));
		elseif ($table == 'articles' && ($published == 0 || $menu == 0)) {
			$db->delete('menu', 'link = ' . $db->quote('index.php?mod=article&id=' . $_POST['id']));
			gcmsNav_compact(2);
		}
			
	}
	// Save config
	elseif (!empty($_POST['configsubmit']) && $GLOBALS['authNamespace']->admin) {
		$db->update('config', array('sitename' => $_POST['sitename'], 
								  'siteauthor' => $_POST['siteauthor'],
								  'sitecontact' => $_POST['sitecontact'],
								  'siteURL' => urldecode($_POST['siteURL']),
								  'sitedesc' => $_POST['sitedesc'],
								  'sitekeywords' => $_POST['sitekeywords'],
								  'siteslogan' => $_POST['siteslogan'],
								  'sitetheme' => $_POST['sitetheme'],
								  'editor' => $_POST['editor'],
								  'googlefeed' => urldecode($_POST['googlefeed']),
								  'imagedir' => $_POST['imagedir'],
								  'forumdir' => $_POST['phpbbdir'],
								  'forumid' => $_POST['phpbbtopic'],
								  'threadintro' => $_POST['threadintro']));
		// If the theme changes we need to clear the entire compiled directory and reload
		$GLOBALS['view']->getEngine()->clear_compiled_tpl();
		header("Location: index.php?mod=admin");
		exit();
	}
	// change password
	elseif (!empty($_POST['newpass']) && $GLOBALS['authNamespace']->admin) {
		if (sha1($_POST['oldpass']) == $config['rootpassword']) {
			if ($_POST['newpass'] == $_POST['conpass'])
				$db->update('config', array('rootpassword' => sha1($_POST['newpass'])));
		}
	}
	// Logout
	elseif (!empty($_GET['action']) && $_GET['action'] == 'logout') {
        $GLOBALS['authNamespace']->admin = false;
        Zend_Session::destroy();
	}
}

function admin_head($db, &$headers, $translate) {
	global $config;
	if (!$GLOBALS['authNamespace']->admin)
		return;
	if ($_GET['action'] == 'config' && !empty($config['forumid'])) {
		$headers->headScript()->captureStart();
		echo <<<CONFIG
		window.addEvent('domready', function() {
			popTopic($('phpbbpath').value, $config[forumid]);			
		});
CONFIG;
		$headers->headScript()->captureEnd();
	}
	if ($config['editor'] == 'FCKeditor') {
		$headers->headScript()->appendFile("./libs/fckeditor/fckeditor.js");
		$headers->headScript()->captureStart();
		echo <<<FCK
		window.addEvent('domready', function() {
			// replace all of the textareas
			$$('#wysiwyg').each(function(e){
				var oFCKeditor = new FCKeditor( e.get('name'), null, null, 'GCMS' );
				oFCKeditor.Config["CustomConfigurationsPath"] = '../../fckgcms.js';
				oFCKeditor.BasePath = "./libs/fckeditor/";
				oFCKeditor.Height = '400';
				oFCKeditor.ReplaceTextarea();
			});
		});
FCK;
		$headers->headScript()->captureEnd();
	}
	elseif ($config['editor'] == 'TinyMCE') {
		$headers->headScript()->appendFile("./libs/tiny_mce/tiny_mce.js");
		$headers->headScript()->captureStart();
		echo <<<MCE
		tinyMCE.init({
			mode : "exact",
			elements : "wysiwyg",
			theme : "advanced",
			plugins : "fullscreen,visualchars",
			theme_advanced_buttons3_add : "separator,visualchars,separator,fullscreen",
			cleanup : false,
			entity_encoding : "raw",
			remove_linebreaks : false,
			forced_root_block : ''
		});
MCE;
		$headers->headScript()->captureEnd();
	}
	$headers->headLink()->appendStylesheet('./modules/admin/datepicker.css');
}

function admin_main($db, &$view, $translate) {
	require_once './libs/phpbb.php';
	global $config;
	if (!empty($config['forumdir']))
		$phpbb = new Zend_PHPBB3($config['forumdir']);
	if ($GLOBALS['authNamespace']->admin) {
        if ($_REQUEST['type'] == 'news')
            $table = 'news';
        else
            $table = 'articles';
		switch ($_GET['action']) {
		case 'manage':
			$data = $db->fetchAll("SELECT * FROM $table ORDER BY pubdate DESC");
			$view->assign('data', $data);
			$view->display('file:../../../modules/admin/manage.tpl');
            break;
		case 'content':
			if (isset($_GET['id'])) {
            	$row = $db->fetchRow("SELECT * FROM $table WHERE id = " . $db->quote($_GET['id']));
            	$menu = $db->fetchRow("SELECT weight FROM menu WHERE link LIKE '%mod=article&id=" . $_GET['id'] . "'");
            } else {
				$row['published'] = 1;
			}
			if ($phpbb)
				$row['approved'] = $phpbb->get_approved($row['comments']);
			$view->assign('row', $row);
            $view->assign('menu', $menu);
			$view->assign('filters', scandir('./filters'));
			$view->display('file:../../../modules/admin/form.tpl');
            break;
		case 'config':
			// Editors
			$view->assign('eOptions', array(
                            '[None]',
                            'FCKeditor',
                            'TinyMCE'));
			$view->assign('config', $config);
			$view->assign('themelist', scandir('./themes'));
			$view->display('file:../../../modules/admin/config.tpl');
			break;
		case 'chgpass':
			$view->display('file:../../../modules/admin/chgpass.tpl');
            break;
		default:
			require './modules/admin/menu.inc';
		}
	}
	else
		$view->display('file:../../../modules/admin/login.tpl');
}

function admin_adminMenu($translate) {
	$stack = array();
	$stack[] = "GCMS Config";
	$stack['action=manage&amp;type=news'] = $translate->_("News Management");
	$stack['action=manage&amp;type=article'] = $translate->_("Article Management");
	$stack['action=config'] = $translate->_("Site Settings");
	$stack['action=chgpass'] = $translate->_("Change Password");
	$stack['action=logout'] = $translate->_("Logout");
	return $stack;
}
?>